package cn.dnui_xqh414.dnuifood_16110100414.SQLite;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RecordDBOperation {
    private String TABLE_NAME = "records";
    private SQLiteDatabase db;

    public RecordDBOperation(RecordSQLiteOpenHelper helper){
        db = helper.getWritableDatabase();
    }

    public void insertData(String tempName){
        db.execSQL("insert into "+TABLE_NAME+"(name) values('"+tempName+"')");
//        db.close();
    }

    public List queryData(String tempName){
        List list = new ArrayList<>();
        Cursor cursor = db.rawQuery(
                "select id as _id, name from "+TABLE_NAME+" where name like '%"+tempName+"%' order by id desc"
                ,null);

        while (cursor.moveToNext()){
//            Map map = new HashMap<>();
//            map.put("name",cursor.getString(cursor.getColumnIndex("name")));
//            list.add(map);
            list.add(cursor.getString(cursor.getColumnIndex("name")));
        }
        return list;
    }

    public boolean hasData(String tempName){
        Cursor cursor = db.rawQuery(
                "select id as _id, name from "+TABLE_NAME+" where name = ?", new String[]{tempName});
        return cursor.moveToNext();
    }

    public List searchData(){
        List list = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from "+TABLE_NAME, null);

        while (cursor.moveToNext()){
//            Map map = new HashMap<>();
//            map.put("name",cursor.getString(cursor.getColumnIndex("name")));
            list.add(cursor.getString(cursor.getColumnIndex("name")));
        }
        return list;
    }

    public void deleteData(){
        db.execSQL("delete from "+TABLE_NAME);
//        db.close();
    }

    public void deleteData_onebyone(String tempName){
        db.execSQL("delete from "+TABLE_NAME+" where name = ?", new String[]{tempName});
    }
}
